package eventReservationServer.eventServerGateway;

import java.util.ArrayList;
import java.util.List;

import javax.jms.*;
import javax.naming.*;

import JMSInternationalEventServer.EventJMSDTO;

import java.io.*;
import java.util.Properties;

public class JMSEventServerGateway implements IEventServerGateway
{

	public List<EventDO> getEvents()
	{
		// Crea lo que va a devolver
		List<EventDO> list = new ArrayList<EventDO>();
		
		String queueName = null;
		Context jndiContext = null;
		QueueConnectionFactory queueConnectionFactory = null;
		QueueConnection queueConnection = null;
		QueueSession queueSession = null;
		Queue queue = null;
		QueueReceiver queueReceiver = null;
		TextMessage textMessage = null;
		ObjectMessage objectMessage = null;
		queueName = "InternationalEventsJMSQueue"; // Lo pongo a mano
//		System.out.println("Queue name is " + queueName);
		try
		{
			Properties props = new Properties();
			props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
					"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
			props.setProperty(Context.PROVIDER_URL, "tcp://localhost:61616");
			props.load(new FileInputStream(
					"EventReservationCore/src/JMSInternationalEventServer/jndi.properties")); // TODO
			jndiContext = new InitialContext(props);
		}
		catch (NamingException e)
		{
			System.out.println("Could not create JNDI API context: "
					+ e.toString());
			System.exit(1);
		}
		catch (IOException ioe)
		{
			System.out.println("Could not find properties file: "
					+ ioe.toString());
			System.exit(1);
		}
		try
		{
			queueConnectionFactory = (QueueConnectionFactory) jndiContext
					.lookup("QueueConnectionFactory");
			queue = (Queue) jndiContext.lookup(queueName);
		}
		catch (NamingException e)
		{
			System.out.println("JNDI API lookup failed: " + e.toString());
			System.exit(1);
		}
		try
		{
			queueConnection = queueConnectionFactory.createQueueConnection();
			queueSession = queueConnection.createQueueSession(false,
					Session.AUTO_ACKNOWLEDGE);
			queueReceiver = queueSession.createReceiver(queue);
			queueConnection.start();
//			while (true)
			{
				Message m = queueReceiver.receive(1);
				if (m != null)
				{
					if (m instanceof TextMessage)
					{
						textMessage = (TextMessage) m;
						System.out.println("Reading message: "
								+ textMessage.getText());
					}
					else if (m instanceof ObjectMessage)
					{
						objectMessage = (ObjectMessage) m;
						EventJMSDTO event = (EventJMSDTO) objectMessage
								.getObject();
						System.out.println("Reading message: "
								+ event.getName() + " " + event.getDate() + " " + event.getDescription() + " " + event.getPlaces());
						
						// Parseo el EventJMSDTO a un EventDO
						EventDO eventDO = new EventDO(0, event.getName(), event.getDate(), event.getDescription(), event.getPlaces());
						list.add(eventDO);
					}
					else
					{
//						break;
					}
				}
			}
		}
		catch (JMSException e)
		{
			System.out.println("Exception occurred: " + e.toString());
		}
		finally
		{
			if (queueConnection != null)
			{
				try
				{
					queueConnection.close();
				}
				catch (JMSException e)
				{
				}
			}
		}

		return list;
	}

	public static void main(String[] args)
	{
		new JMSEventServerGateway().getEvents();
	}
}

/* Este sería el código para hacerlo asíncrono mediante un listener. Faltaría incorporar la clase del listener.

		 List<EventDO> result = null;
		
		 String topicName = null;
		 Context jndiContext = null;
		 TopicConnectionFactory topicConnectionFactory = null;
		 TopicConnection topicConnection = null;
		 TopicSession topicSession = null;
		 Topic topic = null;
		 TopicSubscriber topicSubscriber = null;
		 TextListener topicListener = null;
		 InputStreamReader inputStreamReader = null;
		 String answer = "";
		 // if (args.length != 1) {
		 //
		 System.out.println("Usage: java SimpleTopicSubscriber <topic-name>");
		 // System.exit(1);
		 // }
		 topicName = "MyIso2Topic"; // TODO
		 System.out.println("Topic name is " + topicName);
		 try
		 {
		 Properties props = new Properties();
		 props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
		 "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
		 props.setProperty(Context.PROVIDER_URL, "tcp://localhost:61616");
		 props.load(new FileInputStream(
		 "/home/ander/workspace/ISOProject/EventReservationCore/src/JMSInternationalEventServer/jndi.properties"));
		 // TODO
		 jndiContext = new InitialContext(props);
		 }
		 catch (NamingException e)
		 {
		 System.out.println("Could not create JNDI API context: "
		 + e.toString());
		 e.printStackTrace();
		 System.exit(1);
		 }
		 catch (IOException ioe)
		 {
		 System.out.println("Could not find properties file: "
		 + ioe.toString());
		 System.exit(1);
		 }
		 try
		 {
		 topicConnectionFactory = (TopicConnectionFactory) jndiContext
		 .lookup("TopicConnectionFactory");
		 topic = (Topic) jndiContext.lookup(topicName);
		 }
		 catch (NamingException e)
		 {
		 System.out.println("JNDI API lookup failed: " + e.toString());
		 e.printStackTrace();
		 System.exit(1);
		 }
		 try
		 {
		 topicConnection = topicConnectionFactory.createTopicConnection();
		 topicSession = topicConnection.createTopicSession(false,
		 Session.AUTO_ACKNOWLEDGE);
		 topicSubscriber = topicSession.createSubscriber(topic);
		 topicListener = new TextListener();
		 topicSubscriber.setMessageListener(topicListener);
		 topicConnection.start();
		 System.out.println("To end program, enter Q or q, then <return>");
		 BufferedReader input = new BufferedReader(new InputStreamReader(
		 System.in));
		 do
		 {
		 try
		 {
		 answer = input.readLine();
		 }
		 catch (IOException e)
		 {
		 System.out.println("I/O exception: " + e.toString());
		 }
		 }
		 while (!answer.equalsIgnoreCase("q"));
		 }
		 catch (JMSException e)
		 {
		 System.out.println("Exception occurred: " + e.toString());
		 }
		 finally
		 {
		 if (topicConnection != null)
		 {
		 try
		 {
		 System.out.println("Closing topic connection...");
		 topicConnection.close();
		 }
		 catch (JMSException e)
		 {
		 }
		 }
		 }
*/
